var saveanswer = function(){
    problems[problemidx - 1]['answer'] = $('#problemanswer').val();
    problems[problemidx - 1]['question'] = CKEDITOR.instances.problemquestion.getData();
}

var savedata = function(){
    saveanswer();
    $('#problemcontainer').html('');
    var str = '';
    for(i = 0; i < problems.length; i++){
        str += ('<input type="hidden" name="config[problems]['+i+'][question]" value="'+problems[i]['question']+'"/>');
        str += ('<input type="hidden" name="config[problems]['+i+'][answer]" value="'+problems[i]['answer']+'"/>');
    }
    $('#problemcontainer').append(str);
}

var updatedetail = function(){
    CKEDITOR.instances.problemquestion.setData(problems[problemidx - 1]['question']);
    $('#problemanswer').val(problems[problemidx - 1]['answer']);
}

var updateproblem = function(){
    $('#problemcount').html(problems.length);
    $('#problemslider').slider({
            "max" : problems.length,
            "min" : 1,
            "value" : problemidx
        });
    $('#problemslider').slider("value", problemidx);
    $('#problemchooser').html('');
    for (i = 1; i <= problems.length; i++){
        $('#problemchooser').append('<option value="'+i+'" selected="selected">'+i+'</option>');
    }
    $('#problemchooser').val(problemidx);
}

var problemchooserslide = function(event, ui){
    saveanswer();
    $('#problemchooser').val(ui.value);
    problemidx = ui.value;
    updatedetail();
}

$('#problemchooser').change(function(){
    saveanswer();
    $('#problemslider').slider("value", $(this).val());
    problemidx = $(this).val();
    updatedetail();
})

$('.backslider').click(function(){
    saveanswer();
    if (problemidx > 1) {problemidx--;}
    $('#problemslider').slider("value", problemidx);
    $('#problemchooser').val(problemidx);
    updatedetail();
})

$('.nextslider').click(function(){
    saveanswer();
    if (problemidx < problems.length) {problemidx++;}
    $('#problemslider').slider("value", problemidx);
    $('#problemchooser').val(problemidx);
    updatedetail();
})

$('.deleteproblembutton').click(function(){
    if (confirm('Are you sure want to delete this problem?')){
        if (problems.length == 1){
            alert('Could not delete the only problem left');
        } else {
            //alert(problems.length);
            problems.splice(problemidx - 1, 1);
            if (problemidx > 1){
                problemidx--;
            }
            
            updateproblem();
            updatedetail();
        }
    }
});

$('#newproblembutton').click(function(){
    //alert(problemidx);
    problems.push({"question" : "Question", "answer" : "Answer"});
    problemidx = problems.length;
    updateproblem();
    updatedetail();
})

$('.submitproblems').click(function(){
    savedata();
    return true;
})